package com.xon.lotp.controller;

import com.xon.lotp.pojo.User;
import com.xon.lotp.service.UserService;
import com.xon.lotp.utils.TextFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
@CrossOrigin // 跨域处理
public class UserController {

    @Autowired
    UserService userService;

    @ResponseBody
    @GetMapping("/checkUserName")
    public int checkUserName(String userName) {
        int code = 0;
        boolean result = userService.checkUserName(userName);
        // result true为用户存在
        if (!result) {
            code = 100;
        }
        return code;
    }


    /** 用户登陆验证
     * create by: Xonline
     * create time: 11:03 上午 2021/5/15
     *
     * @Param: User
     * @return code,User
     */
    @ResponseBody
    @RequestMapping(value = "/checkLogin", method = RequestMethod.POST)
    public Map<String, Object> checkLogin(@RequestBody User param, HttpServletRequest request) {
        Map resultMap = new HashMap();
        // 判断用户名是否符合
        if (userService.checkUserName(param.getUserName())) {
            resultMap.put("code", 100); //返回用户名未找到
        } else {
            String userId = userService.checkUserNameAndPwd(param);
            if (userId != null) {
                resultMap.put("data", userService.selectUserByUserId(userId));
                resultMap.put("code", 0); // 返回正常代码 0
            } else {
                resultMap.put("code", 101); // 返回错误代码 101 密码错误
            }
        }
        // 返回数据
        return resultMap;
    }

    /** 用户注册信息录入
     * create by: Xonline
     * create time: 11:04 上午 2021/5/15
     *
     * @Param: User
     * @return code,User
     */
    @ResponseBody
    @RequestMapping(value = "userRegist",method = RequestMethod.POST)
    public Map<String,Object> addUser(@RequestBody User param,HttpServletRequest request){
        Map resultMap = new HashMap();
        // 获取客户端浏览器语言
        String acceptLanguage = request.getHeader("Accept-Language");
        param.setUserLoc(TextFormat.getLanguage(acceptLanguage));

        if (userService.checkUserName(param.getUserName())){
            User user = userService.addUser(param);
            System.out.println(user);
            if(user.getUserId() != null){
                resultMap.put("data",user);
                resultMap.put("code",0);
            }else {
                resultMap.put("code",110);
            }
        }else {
            resultMap.put("code",100);
        }
        return resultMap;
    }
}
